package com.wzy.netty.core.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * 描述  :
 * 创建人:    Wzy
 * 创建时间: 2020-06-11  18:03
 */
public class MyServer {
    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            /*加入一个netty提供的IdleStateHandler*/
                            /**
                             * IdleStateHandler 是netty提供的处理空闲状态的处理器
                             * long readerIdleTime  :  表示多长时间没有读,就会发送一个心跳检测包
                             *  long writerIdleTime : 表示多长时间没有写操作,就会发送一个心跳检测包
                             *  long allIdleTime: 表示多长时间没有进行读写操作,就会发送一个心跳检测包
                             */
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                            /*当IdleStateEvent触发后,就会传递给管道的下一个handel去处理,通过调用触发下一个handel的
                             * userEventTiggered方法,有可能触发读空闲,写空闲,读写空闲*/
                            pipeline.addLast(new MyServerHandel());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
